//===============================
//  功能 ：备注 
//  作者 ：上中野辅亚瑟王 
//  创建时间 ：2023-06-26  10-52-46 
//  Unity版本  ：2019.4.35f1 
//  变更时间 :  2023-06-26  10-52-46 
//===============================





using System;
using System.Collections.Generic;
using UnityEngine;


namespace ZS.U3D.BASE.Runtime.Window
{
	public static class WindowManager
	{


		public static float CanvasScaleFactor { private set;get; }
		public static float DCanvasScaleFactor { private set; get; }

		private static bool _isInitialize = false;
		private static GameObject _driver = null;
		private static Canvas _canvas;
		private static Transform _normal;
		private static Transform _fixed;
		private static Transform _pop;
		private static Transform _toast;

		private static readonly List<UIWindow> _stack = new List<UIWindow>(100);

		/// <summary>
		/// 初始化界面系统
		/// </summary>
		public static void Initalize()
		{
			if (_isInitialize)
			{
				MyDebug.LogWarning($"{nameof(WindowManager)} is initialized !");
				return;
			}

			if (_isInitialize == false)
			{
				// 创建驱动器
				_isInitialize = true;
				_driver = new GameObject($"[{nameof(WindowManager)}]");
				_driver.AddComponent<WindowDriver>();
				UnityEngine.Object.DontDestroyOnLoad(_driver);
				_canvas = UnityEngine.Object.Instantiate(Resources.Load<Canvas>("Canvas"));
				_normal = _canvas.transform.Find("Normal");
				_fixed = _canvas.transform.Find("Fixed");
				_pop = _canvas.transform.Find("Pop");
				_toast = _canvas.transform.Find("Toast");
				_canvas.transform.SetParent(_driver.transform);

				CanvasScaleFactor = _canvas.scaleFactor;
				DCanvasScaleFactor = 1 / CanvasScaleFactor;

				MyDebug.Log($"{nameof(WindowManager)} initalize !");
			}
		}

		/// <summary>
		/// 更新界面系统
		/// </summary>
		internal static void Update()
		{
			if (_isInitialize)
			{
				int count = _stack.Count;
				for (int i = 0; i < _stack.Count; i++)
				{
					if (_stack.Count != count)
						break;
					var window = _stack[i];
					if (window.ActiveSelf)
					{
						window.OnUpdate();
					}
				}
			}
		}

		public static void Destroy() {
			if (_isInitialize)
			{
				_isInitialize = false;

			}
		}

		/// <summary>
		/// 查询窗口是否存在
		/// </summary>
		public static bool HasWindow<T>() where T : UIWindow
		{
			return HasWindow(typeof(T));
		}
		public static bool HasWindow(Type type)
		{
			return IsContains(type.FullName);
		}


		public static void OpenWindow<T>(params object[] userDatas) where T : UIWindow
		{
			OpenWindow(typeof(T), userDatas);
		}

		private static void OpenWindow(Type type, params object[] userDatas)
		{
			string windowName = type.FullName;
			if (IsContains(windowName))
			{
				//已经存在
				UIWindow window = GetWindow(windowName);
				window.SetUserDatas(userDatas);
				window.SetActive(true);
			}
			else
			{
				//不存在
				UIWindow window = CreateInstance(type);
				window.SetUserDatas(userDatas);
				Push(window); //首次压入
				window.InternalLoad();
				window.CanvasGroup.alpha = 0;
				window.SetActive(true);
			}
		}

		public static void HideWindow<T>() where T : UIWindow
		{
			HideWindow(typeof(T));
		}

		public static void HideWindow(Type type)
		{
			string windowName = type.FullName;
			HideWindow(windowName);
		}

		public static void HideWindow(string windowName)
		{
			if (IsContains(windowName))
			{
				UIWindow window = GetWindow(windowName);
				window.SetActive(false);
			}
		}

		public static void HideAllWindows() {
			for (int i = 0; i < _stack.Count; i++)
			{
				UIWindow window = _stack[i];
				window.SetActive(false);
			}
		}

		public static void CloseAllWindows() 
		{ 
			
		}

		public static void CloseWindow<T>() where T : UIWindow {
			CloseWindow(typeof(T));
		}

		private static void CloseWindow(Type type)
		{
			string windowName = type.FullName;
			CloseWindow(windowName);
		}

		private static void CloseWindow(string windowName) {
            if (IsContains(windowName))
            {
				UIWindow window = GetWindow(windowName);
				window.InternalDestroy();
				Pop(window);
			}
		}




		private static bool IsContains(string name)
		{
			for (int i = 0; i < _stack.Count; i++)
			{
				UIWindow window = _stack[i];
				if (window.WindowName == name)
					return true;
			}
			return false;
		}

		private static UIWindow CreateInstance(Type type) {
			UIWindow window = Activator.CreateInstance(type) as UIWindow;

			if (window == null)
				throw new Exception($"Window {type.FullName} create instance failed.");

			//初次初始化
			window.InternalCreate();
			window.Init(type.FullName, GetParent(window.UIWindowType));
			return window;
		}

		private static UIWindow GetWindow(string name)
		{
			for (int i = 0; i < _stack.Count; i++)
			{
				UIWindow window = _stack[i];
				if (window.WindowName == name)
					return window;
			}
			return null;
		}

		private static Transform GetParent(UIWindowType type) {
            switch (type)
            {
                case UIWindowType.Normal:
                    return _normal;
                case UIWindowType.Fixed:
                    return _fixed;
                case UIWindowType.Pop:
                    return _pop;
                case UIWindowType.Toast:
                    return _toast;
                default:
					return _normal;
			}
        }

        private static void Push(UIWindow window)
		{
			// 如果已经存在
			if (IsContains(window.WindowName))
				throw new Exception($"Window {window.WindowName} is exist.");

			// 插入到堆栈
			_stack.Add(window);

		}
		private static void Pop(UIWindow window)
		{
			//如果不存在
			if (!IsContains(window.WindowName))
				throw new Exception($"Window {window.WindowName} is not exist.");
			// 从堆栈里移除
			_stack.Remove(window);
		}


    }
}
